#include "core.cpp"

#define IMGFOLDER "images/"
#define IMGPREFIX "img"
#define IMGEXT ".jpg"
#define IMGCOUNT 100
#define RANGE 20
#define RANGE1 20

int matchMethod = 0;

int main(int argc, char *argv[])
{
  IplImage *img=NULL;
  if(argc!=2)
  {
    cout<<"Usage ./TemplateMatch fileIndex"<<endl;
    exit(-1);
  }
  int i=atoi(argv[1]);
//   for(i=1;i<=IMGCOUNT;i++)
//   {
//     string st = "images/img";
    stringstream ss;
    ss<<"images/img";
    ss<<i;
    ss<<".jpg";
    string file;
    ss>>file;
    img=cvLoadImage(file.c_str());
  if(!img){
    printf("Could not load image file\n");
    exit(0);
  }
//   }
  
  IplImage* grayimg,*newimg;
  newimg=cvCreateImage(cvSize(img->width,img->height),img->depth,img->nChannels);
  cvCopy(img,newimg);
  subtractBackground(newimg);
  grayimg=cvCreateImage(cvSize(img->width,img->height),img->depth,1);
  cvCvtColor(newimg,grayimg,CV_BGR2GRAY);

  cvThreshold(grayimg, grayimg, 1, 255, CV_THRESH_BINARY );
    
  IplImage *result,*templ;
  templ = cvLoadImage("test2.jpg",CV_LOAD_IMAGE_GRAYSCALE);
  result = cvCreateImage(cvSize(grayimg->width-templ->width+1,grayimg->height-templ->height+1),32,1);
  
  /// Do the Matching and Normalize
  cvMatchTemplate( grayimg, templ, result, matchMethod );
  cvNormalize( result, result);
  
  double minVal; double maxVal; CvPoint minLoc; CvPoint maxLoc;
  CvPoint matchLoc;
  cvMinMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc);
  
  if( matchMethod  == CV_TM_SQDIFF || matchMethod == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
  else  
    { matchLoc = maxLoc; }
  
  cvRectangle(img,cvPoint(matchLoc.x,matchLoc.y),cvPoint(matchLoc.x+templ->width,matchLoc.y+templ->height),cvScalar(255));
  // create a window
  cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE); 
  cvMoveWindow("mainWin", 100, 100);
  cvNamedWindow("mainWin1", CV_WINDOW_AUTOSIZE); 
  cvMoveWindow("mainWin1", 400, 100);

  // show the image
  cvShowImage("mainWin", grayimg);
  cvShowImage("mainWin1", img);

  // wait for a key
  cvWaitKey(0);

  // release the image
  cvReleaseImage(&img );
  return 0;
}